package com.dacool.view;

import static com.dacool.util.ViewUtils.rp;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap.Config;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import android.widget.ImageView.ScaleType;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Scroller;

import com.dacool.app.sale.R;
import com.lidroid.xutils.BitmapUtils;

public class MyImageViewPager extends ViewPager implements OnClickListener {

	private ArrayList<Integer> ids;
	private ArrayList<String> urls;
	private BitmapUtils bmUtils;
	boolean canScroll = true;
	Handler mHandler;
	
	private long scrollInterval = 5000;
	
	public void setScrollInterval(long scrollInterval) {
		this.scrollInterval = scrollInterval;
	}

	private boolean autoScroller = true;

	public void setAutoScroller(boolean autoScroller) {
		this.autoScroller = autoScroller;
	}

	private MyViewPagerDelegate delegate;

	public void setDelegate(MyViewPagerDelegate delegate) {
		this.delegate = delegate;
	}

	public static interface MyViewPagerDelegate {
		public void didTapAtView();
	}

	public void setDrawableIDs(List<Integer> ids) {
		this.ids = new ArrayList<Integer>(ids);
		this.urls = null;
		this.getAdapter().notifyDataSetChanged();
		this.setCurrentItem(500, false);
	}

	public void setImageUrls(List<String> urls) {
		this.urls = new ArrayList<String>(urls);
		this.ids = null;
//		Log.d("test", "urls:" + urls.get(0));
		this.getAdapter().notifyDataSetChanged();
		this.setCurrentItem(500, false);
	}

	public MyImageViewPager(Context context) {

		this(context, null);
	}

	public MyImageViewPager(Context context, AttributeSet attrs) {
		super(context, attrs);

		bmUtils = new BitmapUtils(context);
		bmUtils.configDiskCacheEnabled(true);
		// bmUtils.clearCache();
//		 bmUtils.configDefaultLoadingImage(R.drawable.bannerimg);
//		 bmUtils.configDefaultLoadFailedImage(R.drawable.bannerimg);
		bmUtils.configDefaultBitmapConfig(Config.ARGB_8888);
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				if (!autoScroller)
					return;
				if (canScroll) {
					int item = MyImageViewPager.this.getCurrentItem();
					if (item == MyImageViewPager.this.getAdapter().getCount() - 1) {
						MyImageViewPager.this
								.setCurrentItem(MyImageViewPager.this
										.getAdapter().getCount() / 2, false);
					} else
						MyImageViewPager.this.setCurrentItem(item + 1);
				}
				this.sendEmptyMessageDelayed(100, scrollInterval);
			}
		};

		this.setAdapter(new PagerAdapter() {
			@Override
			public boolean isViewFromObject(View arg0, Object arg1) {
				// TODO Auto-generated method stub
				return arg0 == arg1;
			}

			@Override
			public int getCount() {
				if (MyImageViewPager.this.getRealCount() == 0)
					return 0;
				return 1000;
			}

			@Override
			public Object instantiateItem(ViewGroup container, int position) {
				int realpos = ((position + 500) % 1000)
						% MyImageViewPager.this.getRealCount();
				RelativeLayout rl = new RelativeLayout(getContext());
				ImageView iv = new ImageView(getContext());
//				iv.setCornerRadius((int) rp(10));
				iv.setBackgroundColor(Color.TRANSPARENT);
				iv.setScaleType(ScaleType.FIT_XY);
				RelativeLayout.LayoutParams rlp = new android.widget.RelativeLayout.LayoutParams(
						android.widget.RelativeLayout.LayoutParams.MATCH_PARENT,
						android.widget.RelativeLayout.LayoutParams.MATCH_PARENT);
				rlp.setMargins((int) rp(10), (int) rp(10), (int) rp(10),
						(int) rp(10));
				rl.addView(iv, rlp);
				container.addView(rl,
						android.view.ViewGroup.LayoutParams.MATCH_PARENT,
						android.view.ViewGroup.LayoutParams.MATCH_PARENT);
				if (ids != null) {
					iv.setImageResource(ids.get(realpos));
					iv.setTag("" + ids.get(realpos));
				} else if (urls != null) {
					bmUtils.display(iv, urls.get(realpos));
					iv.setTag(urls.get(realpos));
				}
				rl.setOnClickListener(MyImageViewPager.this);
				return rl;
			}

			@Override
			public void destroyItem(ViewGroup container, int position,
					Object object) {
				container.removeView((View) object);
			}
		});
		try {
			Field mScroller;
			mScroller = ViewPager.class.getDeclaredField("mScroller");
			mScroller.setAccessible(true);
			FixedSpeedScroller scroller = new FixedSpeedScroller(
					this.getContext());
			// scroller.setFixedDuration(5000);
			mScroller.set(this, scroller);
		} catch (NoSuchFieldException e) {
		} catch (IllegalArgumentException e) {
		} catch (IllegalAccessException e) {
		}
		mHandler.sendEmptyMessageDelayed(100, scrollInterval);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (delegate != null) {
			delegate.didTapAtView();
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent arg0) {
		// TODO Auto-generated method stub
		if (arg0.getAction() != MotionEvent.ACTION_CANCEL
				&& arg0.getAction() != MotionEvent.ACTION_UP) {
			canScroll = false;
		} else {
			canScroll = true;
		}
		return super.onTouchEvent(arg0);
	}

	public int getRealCount() {
		int realCount = ids != null ? ids.size() : urls != null ? urls.size()
				: 0;
		return realCount;
	}

	private class FixedSpeedScroller extends Scroller {

		private int mDuration = 800;

		public FixedSpeedScroller(Context context) {
			super(context);
		}

		public FixedSpeedScroller(Context context, Interpolator interpolator) {
			super(context, interpolator);
		}

		// // public FixedSpeedScroller(Context context, Interpolator
		// interpolator,
		// boolean flywheel) {
		// super(context, interpolator, flywheel);
		// }

		@Override
		public void startScroll(int startX, int startY, int dx, int dy,
				int duration) {
			// Ignore received duration, use fixed one instead
			super.startScroll(startX, startY, dx, dy, mDuration);
		}

		@Override
		public void startScroll(int startX, int startY, int dx, int dy) {
			// Ignore received duration, use fixed one instead
			super.startScroll(startX, startY, dx, dy, mDuration);
		}
	}
}
